package personnal.blogprinter;

import java.util.Queue;

import org.apache.log4j.Logger;

import personnal.blogprinter.data.PostError;
import personnal.blogprinter.data.PostRange;
import personnal.blogprinter.data.Settings;
import personnal.blogprinter.exceptions.NetworkException;

public class BlogWorker implements Runnable {

	private static Logger logger = Logger.getLogger(BlogWorker.class);

	protected Queue<PostRange> readQueue;
	protected Queue<PostError> errorQueue;
	protected WordpressClient client;
	protected WorkDoneListener workDoneListener;

	public BlogWorker(Settings settings, Queue<PostRange> inQueue, Queue<PostError> errorQueue) throws NetworkException {
		super();
		this.readQueue = inQueue;
		this.errorQueue = errorQueue;
		this.client = createClient(settings);
	}

	protected WordpressClient createClient(Settings settings) throws NetworkException {
		return new WordpressClient(settings);
	}

	public void run() {
		logger.info("Started ...");
		PostRange postRange = null;
		BlogPostHandler blogPostHandler = createPostHandler();
		while ((postRange = readQueue.poll()) != null) {
			blogPostHandler.handlePostRange(postRange);
		}
		logger.info("No more postRange to handle");
		if (workDoneListener != null) {
			workDoneListener.workDone();
		}
		logger.info("Exiting ...");
	}

	protected BlogPostHandler createPostHandler() {
		return new BlogPostHandler(client, errorQueue);
	}

	public WorkDoneListener getWorkDoneListener() {
		return workDoneListener;
	}

	public void setWorkDoneListener(WorkDoneListener workDoneListener) {
		this.workDoneListener = workDoneListener;
	}
}
